﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.IO;
using Common;
using YQBlog.General;
using res = Resource.Controllers.Uploadify.Uploadify;
using System.Globalization;

namespace YQBlog.Controllers
{
    public class UploadifyController : Controller
    {
        GeneralConfigInfo configinfo = YQBlog.General.WebUtils.configinfo;

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)//传参
        {
            Response.Charset = "UTF-8";
            //string inputname = "filedata";//表单文件域name
            string attachdir = "/upload/photo";// 上传文件保存路径，结尾不要带/
            int dirtype = 2; // 1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
            int maxattachsize = 2097152;     // 最大上传大小，默认是2M
            string upext = "jpg,gif,png";    // 上传扩展名
            int msgtype = 2;                 //返回上传参数的格式：1，只返回url，2，返回参数数组
            string immediate = Request.QueryString["immediate"];//立即上传模式，仅为演示用
            byte[] file;                     // 统一转换为byte数组处理
            string localname = "";
            string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];

            string err = "";
            string msg = "''";

            if (disposition != null)
            {
                // HTML5上传
                file = Request.BinaryRead(Request.TotalBytes);
                localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名
            }
            else
            {
                // 读取原始文件名
                localname = fileData.FileName;
                // 初始化byte长度.
                file = new Byte[fileData.ContentLength];

                // 转换为byte类型
                System.IO.Stream stream = fileData.InputStream;
                stream.Read(file, 0, fileData.ContentLength);
                stream.Close();
            }

            if (file.Length == 0) err = res.Uploadify_NoData_Tip;
            else
            {
                if (file.Length > maxattachsize) err = res.Uploadify_Size_Tip + maxattachsize + res.Byte;
                else
                {
                    string attach_dir, attach_subdir, filename, extension, target;

                    // 取上载文件后缀名
                    extension = GetFileExt(localname);

                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = res.Uploadify_Extension_Tip + upext;
                    else
                    {
                        switch (dirtype)
                        {
                            case 2:
                                attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
                                break;
                            case 3:
                                attach_subdir = "ext_" + extension;
                                break;
                            default:
                                attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
                                break;
                        }
                        attach_dir = attachdir + "/" + attach_subdir + "/";

                        // 生成随机文件名
                        Random random = new Random(DateTime.Now.Millisecond);
                        filename = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + "." + extension;

                        target = attach_dir + filename;
                        try
                        {
                            CreateFolder(Server.MapPath("~/" + attach_dir));

                            System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/" + target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                            fs.Write(file, 0, file.Length);
                            fs.Flush();
                            fs.Close();
                            CreateThumbnail(target, attach_dir, filename);
                        }
                        catch (Exception ex)
                        {
                            err = ex.Message.ToString();
                        }

                        // 立即模式判断
                        if (immediate == "1") target = "!" + target;
                        target = jsonString(target);
                        if (msgtype == 1) msg = "'" + target + "'";
                        else msg = "{'url':'" + target + "','localname':'" + jsonString(localname) + "'}";
                    }
                }
            }
            file = null;

            return this.Content("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
        }

        string jsonString(string str)
        {
            str = str.Replace("\\", "\\\\");
            str = str.Replace("/", "\\/");
            str = str.Replace("'", "\\'");
            return str;
        }

        string GetFileExt(string FullPath)
        {
            if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
            else return "";
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        void CreateFolder(string FolderPath)
        {
            if (!System.IO.Directory.Exists(FolderPath)) System.IO.Directory.CreateDirectory(FolderPath);
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        void CreateThumbnail(string pic,string path,string filename)
        {
            if (configinfo.ThumbnailInfo.Trim() != "")
            {

                foreach (string s in configinfo.ThumbnailInfo.Split(new char[] { ',' }))
                {
                    string[] ss = s.Split(new char[] { 'x' });
                    if (ss.Length == 2)
                    {
                        int w = Utils.StrToInt(ss[0]);
                        int h = Utils.StrToInt(ss[1]);
                        if (w > 0 && h > 0)
                        {
                            CreateFolder(Server.MapPath("~/" + path + s+"/"));
                            Thumbnail.MakeThumbnailImage(Server.MapPath("~/" + pic), Server.MapPath("~/" + path + s + "/") + filename, w, h);
                        }
                    }
                }
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ContentResult Import(HttpPostedFileBase FileData, string folder, string name)
        {
            string result = "";
            if (null != FileData)
            {
                try
                {
                    string extension = Path.GetExtension(FileData.FileName).ToLower();
                    // 生成随机文件名 
                    Random random = new Random(DateTime.Now.Millisecond);
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + "." + extension;
                    saveFile(FileData, filename);  
                }
                catch
                {
                    result = "";
                }
            }
            return Content(result);
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        [NonAction]
        private void saveFile(HttpPostedFileBase postedFile, string saveName)
        {
            string phyPath = Request.MapPath("~/upload/photo/");
            if (!Directory.Exists(phyPath))
            {
                Directory.CreateDirectory(phyPath);
            }
            try
            {
                postedFile.SaveAs(phyPath + saveName);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }

    }
}